// pages/giftSel/giftgiftSel.js
const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: false,
    circular: false,
    lastTime: 0,
    current: 0,
    indicatorDots: true,
    items: [],
    jiugui_items: [],
    jiugui_page: 1,
    jiugui_total_page: 0,
    pingtai_page: 1,
    pingtai_total_page:0,
    pingtai_items: [],
    coupons_items: [],
    coupons_page: 1,
    coupons_total_page: 0,
    total_num: 0,
    total_price: 0,
    limit: 10,
    show_type: 1, //1:酒柜 2:平台
    buyGoods: [], //购买商品列表
    common: true, //普通礼品卡
    luck: false,  //手气礼品卡
    maskLayer:true,  //弹窗
    luckNumber:2,    //礼品卡默认个数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      cardId: options.id
    })
    if (options.sku_code){
      this.setData({
        sku_code: options.sku_code
      })
    }
     if (options.coupons_selectedId) {
        this.setData({
           coupons_selectedId: options.coupons_selectedId,
           show_type:3
        })
     }
    this.cardImage();
    this.wineList();
    this.goodsList();
     this.couponsList();
  },

  changeType: function (e) {
    var that = this;
    this.setData({
      show_type: e.currentTarget.dataset.type,
      items: (e.currentTarget.dataset.type == 1 ? that.data.jiugui_items : that.data.pingtai_items)
    })
  },

  //页面上拉触底
  onReachBottom: function (e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function () {
    var that=this;
    if (that.data.show_type==1){  //加载更多我的酒柜
      if (this.data.jiugui_page >= this.data.jiugui_total_page) {
        return;
      }
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        jiugui_page: this.data.jiugui_page + 1
      });
      this.wineList();
    } else if (that.data.show_type == 2){  //加载更多平台购酒
      if (this.data.pingtai_page >= this.data.pingtai_total_page) {
        return;
      }
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        pingtai_page: this.data.pingtai_page + 1
      });
      this.goodsList();
    }else{  //加载更多餐券
       if (this.data.coupons_page >= this.data.coupons_total_page) {
          return;
       }
       wx.showLoading({
          title: '加载中',
       })
       this.setData({
          coupons_page: this.data.coupons_page + 1
       });
       this.couponsList();
    }
  },
  //卡面图片列表
  cardImage: function () {
    var that = this;
    api.POST({
      params: {
        cid: that.data.cardId,
      },
      url: app.globalData.base_url + 'Giftcard/details',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            cardImage: res.data.data.img_list
          });
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("请检查网络");
      }
    })
  },

   //餐券列表
   couponsList: function () {
      var params = new Object()
      var that = this;
      var selectedId = that.data.coupons_selectedId;
      params.page = that.data.coupons_page;
      params.limit = that.data.limit;
      params.type = 4;
      if (selectedId){
         params.meal_ticket_id = selectedId;
      }
      api.POST({
         params: params,
         url: app.globalData.base_url + 'Mealticket/list',
         success: function (res) {
            wx.hideLoading()
            if (util.isEmpty(res.data.code)) {
               var paging = res.data.data.paging;
               var totalPage = paging.total_page;
               var orderList = res.data.data.list;
               orderList = orderList.map(function (item) {
                  if (item.meal_ticket_id == selectedId) {
                     item.selected = 1
                  } else {
                     item.selected = 0
                  }
                  return item
               })
               if (that.data.page == 1) {
                  var itemData = orderList;
               } else {
                  var itemData = that.data.coupons_items.concat(orderList)
               }

               var selectedProduct = itemData.filter(function (item) {
                  return item.selected == 1
               })

               that.setData({
                  coupons_total_page: totalPage,
                  coupons_items: itemData,
                  selectedCouponsProduct: selectedProduct
               })
               that.total_num()
            } else {
               util.showError(res.data.message);
            }
         },
         fail: function (fail) {
            util.showError("请检查网络");
         }
      })
   },

   //商品勾选
   selectedCol: function (e) {
      var index = e.currentTarget.dataset.index;
      var data = this.data.coupons_items;
      if (data[index].selected == 0) {
         data[index].selected = 1
      } else {
         data[index].selected = 0
      }
      var selectedProduct = data.filter(function (item) {
         return item.selected == 1
      })
      this.setData({
         coupons_items: data,
         selectedCouponsProduct: selectedProduct
      })
      this.total_num()
   },

  //酒柜列表
  wineList: function () {
    var that = this;
    api.POST({
      params: {
        page: that.data.jiugui_page,
        limit: that.data.limit,
        status: 1
      },
      url: app.globalData.base_url + 'winecabinet/index',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.paging;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var count = paging.count;
          var resultList = res.data.data.list;
          resultList = that.doData(resultList);
          if (currentPage == 1) {
            var itemData = resultList;
          } else {
            var itemData = that.data.jiugui_items.concat(resultList)
          }
          let num = itemData.filter(function (item, index) {
            return item.sku_code == that.data.sku_code
          })
          if (num.length > 0) {
            let index = itemData.indexOf(num[0]);
            if (index >= 0) {
              itemData.splice(index, 1);
              itemData.unshift(num[0]);
              if (currentPage == 1){
                num[0].current_num = 1;
                that.setData({
                  total_num: 1
                })
              }
              
            }
          }
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            jiugui_total_page: totalPage,
            jiugui_items: itemData,
            items: (that.data.show_type == 1 ? itemData : that.data.pingtai_items)
          });
        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //处理数据
  doData: function (list) {
    if (list.length <= 0) {
      return [];
    }
    var newList = [];
    for (var i = 0; i < list.length; i++) {
      if (list[i].expired ==1){
        var expired = 1
      }else{
        var expired = 0
      }
      var item = {
        id: list[i].id,
        images: list[i].image,
        name: list[i].gname,
        price: list[i].current_price,
        num: list[i].num,
        sku_code: list[i].sku_code,
        volume: list[i].volume,
        degree: list[i].degree,
        current_num: 0,
        isTouchMove: false,
        expired: expired
      }
      newList.push(item)
    }
    return newList;
  },

  //平台购酒商品列表
  goodsList: function () {
    var that = this;
    api.POST({
      params: {
        page: that.data.pingtai_page,
        limit: that.data.limit,
      },
      url: app.globalData.base_url + 'goods/getList',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.search;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var resultList = res.data.data.goods_list;
          resultList = that.doPingtaiData(resultList);
          if (currentPage == 1) {
            var itemData = resultList;
            if (itemData.length >= 1) {
              //有数据
            } else {
              //无数据
            }
          } else {
            var itemData = that.data.pingtai_items.concat(resultList)
          }
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            pingtai_total_page: totalPage,
            pingtai_items: itemData,
            items: (that.data.show_type == 2 ? itemData : that.data.jiugui_items)
          });
        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //处理数据
  doPingtaiData: function (list) {
    if (list.length <= 0) {
      return [];
    }
    var newList = [];
    for (var i = 0; i < list.length; i++) {
      var item = {
        id: list[i].id,
        images: list[i].image,
        name: list[i].gname,
        price: list[i].current_price,
        num: '',
        sku_code: list[i].sku_code,
        volume: list[i].volume,
        degree: list[i].degree,
        current_num: 0,
        isTouchMove: false,
      }
      newList.push(item)
    }
    return newList;
  },

   //手动输入数量
   inputNumber: function (e) {
      var that = this;
      var num = e.detail.value;
      num = num.replace(/^0/, '');
      var reg = /^\s*$/g;
      var info = e.currentTarget.dataset.info;
      var i = e.currentTarget.dataset.i;
      var items = that.data.items;
      if (reg.test(num) || num == null || num == "") {
         info.current_num = '';
      } else {
         if (info.num == '' || info.num == undefined){
            info.current_num = num;
         }else{
            if (num <= info.num/1) {
               info.current_num = num;
            } else {
               util.showError("库存不足");
               info.current_num = info.num;
            }
         }
         
      }
      items[i] = info;
      if (that.data.show_type == 1) {
         this.setData({
            items: items,
            jiugui_items: items
         })
      } else {
         that.setData({
            items: items,
            pingtai_items: items
         })
      }
      that.total_num()
   },

   //检查输入数量是否为空
   checkInputNumber: function (e) {
      var that = this;
      var info = e.currentTarget.dataset.info;
      var i = e.currentTarget.dataset.i;
      if (info.current_num == '') {
         info.current_num = 0;
         var items = that.data.items;
         items[i] = info;
         if (that.data.show_type == 1) {
            this.setData({
               items: items,
               jiugui_items: items
            })
         } else {
            that.setData({
               items: items,
               pingtai_items: items
            })
         }
         that.total_num()
      }
   },

  //增加
  addNum: function (e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (that.data.show_type == 1) {
      if (info.current_num < info.num) {
         info.current_num = (++info.current_num)
        var items = that.data.jiugui_items
        items[i] = info;
        that.setData({
          items: items,
          jiugui_items: items
        })
        that.total_num()
      }
    } else {
       info.current_num = (++info.current_num)
      var items = that.data.pingtai_items
      items[i] = info;
      that.setData({
        items: items,
        pingtai_items: items
      })
      that.total_num()
    }

  },
  //减少
  minusNum: function (e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (info.current_num >= 1) {
      info.current_num = (info.current_num - 1)
      var items = (that.data.show_type == 1 ? that.data.jiugui_items : that.data.pingtai_items)
      items[i] = info;
      if (that.data.show_type == 1) {
        that.setData({
          items: items,
          jiugui_items: items
        })
      } else {
        that.setData({
          items: items,
          pingtai_items: items
        })
      }
      that.total_num()
    }
  },
  //总数量
  total_num: function () {
    var that = this;
    setTimeout(function(){
       var total_num = 0;
       var items = that.data.jiugui_items;
       for (var i = 0; i < items.length; ++i) {
          if (items[i].current_num != '') {
             total_num += items[i].current_num/1;
          }
       }
      
       var couponsNum = that.data.selectedCouponsProduct.length;
       total_num += couponsNum;
       var total_price = 0;
       var buyGoods = []
       var pingtai_items = that.data.pingtai_items;
       for (var i = 0; i < pingtai_items.length; i++) {
          if (pingtai_items[i].current_num > 0) {
             total_num += pingtai_items[i].current_num/1;
             var box = {};
             box.sku_code = pingtai_items[i].sku_code;
             box.num = pingtai_items[i].current_num;
             buyGoods.push(box);
             var num = pingtai_items[i].current_num;
             var price = pingtai_items[i].price / 1;
             total_price += (num * price);
          }
       }
       that.setData({
          buyGoods: buyGoods,
          total_price: total_price.toFixed(2),
          total_num: total_num
       })
    },0)
  },

  //支付并生成礼品卡
  submit: function () {
    var that = this;
    setTimeout(function(){
       var text = ''
       var jiugui_items = that.data.jiugui_items;
       jiugui_items.forEach((currentValue) => {
          // console.log(currentValue);
          if (currentValue.expired == 1 && currentValue.current_num > 0) {
             text += currentValue.name + '、'
          }
       })
       text = text.replace(/、$/, "");
       if (text) {
          wx.showModal({
             title: '提示',
             content: '礼品卡中含有活动赠品（' + text + '），将于今日24点过期，请提醒好友及时领取。赠品过期不会影响好友领取您送出的其他商品。',
             success(res) {
                if (res.confirm) {
                   if (that.data.total_num > 0) {
                      if (that.data.total_num == 1) {
                         if (that.data.buyGoods.length > 0) {
                            //购买了平台商品，需支付
                            that.payOrder();
                         } else {
                            that.createCard(); //生成礼品卡
                         }
                      } else {
                         that.setData({
                            maskLayer: false
                         })
                      }
                   }
                } else if (res.cancel) {
                   // console.log('用户点击取消')
                }
             }
          })
          return false
       }

       if (that.data.total_num > 0) {
          if (that.data.total_num == 1) {
             if (that.data.buyGoods.length > 0) {
                //购买了平台商品，需支付
                that.payOrder();
             } else {
                that.createCard(); //生成礼品卡
             }
          } else {
             that.setData({
                maskLayer: false
             })
          }
       }else{
          util.showError("请选择商品");
       }
    },1000)

  },

  

  //拼手气礼品卡提交
  luckSubmit:function(e){

    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }

    var total_num = this.data.total_num;
    var luckNumber = this.data.luckNumber;
    if (luckNumber / 1 > total_num / 1 && this.data.luck){
      util.showError("礼品卡个数不能大于所选商品数量");
      return false;
    }

    if (this.data.buyGoods.length > 0) {
      //购买了平台商品，需支付
      this.payOrder();
    } else {
      this.createCard(); //生成礼品卡
    }
  },

//关闭弹窗
  maskLayerCol:function(){
    this.setData({
      maskLayer: true,
      common: true,
      luck: false
    })
  },

  //阻止事件穿透
  maskLayerFalse:function(){
    return false
  },

  //修改手气红包个数
  luckNumberModify:function(e){
    var num = e.detail.value;
    var re = /^[0-9]+$/;
    if (re.test(num) && num >= 1) {
      this.setData({
        luckNumber: num
      })
    }else{
      this.setData({
        luckNumber: this.data.luckNumber
      })
    }

  },

//切换为拼手气礼品卡
  luckSelect:function(){
    this.setData({
      common: false,
      luck:true
    })
  },

  //切换为普通礼品卡
  commonSelect: function () {
    this.setData({
      common: true,
      luck: false,
      luckNumber:2
    })
  },



  // 支付订单
  payOrder: function () {
    var that = this;
    var buyGoods = that.data.buyGoods;
    var params = new Object()
    params.record = JSON.stringify(buyGoods)
    params.buy_type = 1;
    util.showLoading("加载中");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          wx.removeStorageSync('shopId')
          that.wxPayOrder(res.data.data.result.oid, res.data.data.result.type);
        } else if (res.data.code == "2499") {
          util.showError("库存不足");
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //支付接口
  wxPayOrder: function (oid, types) {
    var params = new Object()
    var that = this;
    params.oid = oid;
    api.POST({
      params: { oid: oid },
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              that.createCard(); //生成礼品卡
            },
            fail: function (error) {
              util.showError("支付失败");
              that.deleteOrder(oid);
              wx.removeStorageSync('orderData');
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },

  //删除订单
  deleteOrder: function (oid) {
    var that = this;
    api.POST({
      params: { oid: oid, type: 1 },
      url: app.globalData.base_url + 'couponsorder/del',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.onShow();
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("请检查网络");
      }
    })
  },

  //生成礼品卡
  createCard: function () {
    var that = this;
    var index = that.data.current;
    var buyGoods=[];
    
    for (var i = 0; i < that.data.buyGoods.length; i++){
      buyGoods.push(that.data.buyGoods[i]);
    }

    var jiugui_items = that.data.jiugui_items;
    for (var i = 0; i < jiugui_items.length; i++) {
      if (jiugui_items[i].current_num > 0) {
        var box = {};
        box.sku_code = jiugui_items[i].sku_code;
        box.num = jiugui_items[i].current_num;
        buyGoods.push(box);
      }
    }

     var selectedCouponsProduct = that.data.selectedCouponsProduct;
     for (var i = 0; i < selectedCouponsProduct.length; i++) {
           var box = {};
           box.meal_ticket_id = selectedCouponsProduct[i].meal_ticket_id;
           box.num = 1;
           buyGoods.push(box);
     }


    var params = new Object()
    params.record = JSON.stringify(buyGoods)
    params.cid = that.data.cardId;
    params.form_id = this.data.formId;
    params.img_id = that.data.cardImage[index].img_id;
    if (that.data.luck==true){
      var re = /^[1-9]\d*$/;
      var num = that.data.luckNumber;
      if (re.test(num) && num>=1){
        params.num = that.data.luckNumber
      }else{
        util.showError("礼品卡个数必须为大于等于1的整数");
        return false
      }
      
    }
   //   console.log(params);
   //   return false;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'giftcard/CreateCard',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          wx.redirectTo({
            url: '/play/pages/giftShare/giftShare?show_type=3&linkCode=' + res.data.data.linkCode
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
  bindchange:function(e){
    var current = e.detail.current;
    this.setData({
      current: current
    })
  },
  cardSelect:function(e){
    var current = e.currentTarget.dataset.index
    this.setData({
      current: current
    })
  },
  //表单提交事件
  formSubmit: function (e) {

    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }
    this.setData({
      formId: e.detail.formId
    })
    this.submit();
  },
  emptyLuckNumber:function(){
    this.setData({
      luckNumber:''
    })
  }
})